<?php
namespace Peas\Http;

/**
 * Peas Framework
 *
 * Http工具类
 *
 * @author  Hongzan Zhang <zhanghongzan@163.com>
 * @version $Id$
 */
class HttpUtils
{
    /**
     * 发送post请求
     *
     * @param  string $url   url地址
     * @param  array  $param 参数
     * @return mixed
     */
    public static function post($url, $param = [])
    {
        $options = ['http' => ['method'  => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($param)]];
        $context = stream_context_create($options);
        return file_get_contents($url, false, $context);
    }

    /**
     * 跳转
     *
     * @param string $url  目标地址
     * @param int    $time 延迟时间（秒）,默认为0
     * @param string $msg  输出信息，默认为空
     */
    public static function redirect($url, $time = 0, $msg = '')
    {
        if (!headers_sent()) {
            if (0 === $time) {
                header('Location: ' . $url);
            } else {
                header("refresh:{$time};url={$url}");
                echo($msg);
            }
            exit();
        } else {
            $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
            if ($time != 0) {
                $str .= $msg;
            }
            exit($str);
        }
    }

    /**
     * 获取访问IP地址
     *
     * @return string
     */
    public static function getClientIp()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
            return getenv("HTTP_CLIENT_IP");
        } elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
            return getenv("HTTP_X_FORWARDED_FOR");
        } elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
            return getenv("REMOTE_ADDR");
        } elseif (array_key_exists('REMOTE_ADDR', $_SERVER) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
            return $_SERVER ['REMOTE_ADDR'];
        }
        return "unknown";
    }

    /**
     * 判断是否为手机浏览器
     *
     * @return boolean
     */
    public static function isMobile()
    {
        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }
        $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $clientKeywords = 'mobile|iphone|android|ipod|samsung|nokia|sony|ericsson|mot|htc|sgh|lg|sharp|sie-|philips|panasonic|alcatel|lenovo|blackberry|meizu|netfront|symbian|ucweb|windowsce|palm|operamini|operamobi|opera mobi|openwave|nexusone|cldc|midp|wap';
        return preg_match("/(" . $clientKeywords . ")/i", $userAgent) && (strpos($userAgent, 'ipad') === false);
    }

    /**
     * 获取当前访问的完整URL
     *
     * @return string
     */
    public static function getUrl()
    {
        $protocal  = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $phpSelf   = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $pathInfo  = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relateUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $phpSelf . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $pathInfo);
        return $protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relateUrl;
    }
}
